package com.panshi.modules.common.service;

import com.alibaba.fastjson.JSON;
import com.panshi.api.bean.ArticleBean;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;

import java.util.UUID;

/**
 * @author :jiege
 * @description :
 * @create :2020-08-25 10:58:00
 */
@Configuration
@Service
public class ArctcleService {

    @Autowired
    private RabbitTemplate rabbitTemplate;//mq

    public static final  String EX_NAME="my-queue-article";
    @Autowired
    ConfirmCallback confirmCallback;

    public void send(ArticleBean articleNoBean) {
        rabbitTemplate.setConfirmCallback(confirmCallback);
        //生产一个消息ID
        String msgId= UUID.randomUUID().toString();
        rabbitTemplate.convertAndSend(EX_NAME,"", JSON.toJSONString(articleNoBean),message -> {
            message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);//对消息做持久化处理
            message.getMessageProperties().setCorrelationId(msgId);
            return message;
        },new CorrelationData(msgId));
    }

    //定义了一个发送到交换器确认回调类
    @Component
    class MyConfirmCallback implements RabbitTemplate.ConfirmCallback {
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            // 1.如果消息没有到exchange,则confirm回调,ack=false
            // 2.如果消息到达exchange,则confirm回调,ack=true
            if(ack) {
                System.out.println(EX_NAME+",发送消息到ex成功,id="+correlationData.getId());
                //删除
            }else {
                System.out.println(EX_NAME+",发送消息到ex失败,id="+correlationData);
                //重新发送
                //写入db，用一个定时任务去发生，人工发送
            }
        }

    }
}
